package com.ubxtech.core.context;

import com.ubxtech.core.exception.ErrorCode;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

/**
 * @author Victor.Xiao
 * @since 2022-01-14 10:22
 **/
@Data
public class Result<T> {

    /** 错误代码 **/
    @Schema(title="200表示正确返回结果集，非200 data将为空")
    private Integer code;

    /** 返回结果说明 **/
    @Schema(title="返回信息说明 success 表示正确返回，否则返回错误信息")
    private String msg;

    @Schema(title="结果数据，统一封装在data中")
    private T data;



    public Result(T data) {
        this(200, "success",data);

    }
    public Result() {
        this(200,"success");

    }


    public Result(ErrorCode errorCodeEnum) {
        this.code = errorCodeEnum.getCode();
        this.msg = errorCodeEnum.getMessage();
    }


    public Result(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Result(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data =data;
    }

    public static  <T> Result<T> error(String msg) {
        Result<T> r = new Result<>();
        r.errorMsg(500, msg);
        return r;
    }

    public static  <T> Result<T> error() {
        Result<T> r = new Result<>();
        r.errorMsg(500, "出现异常了，请与管理员联系");
        return r;
    }

    public static <T> Result<T> ok(T data) {
        return new Result<>(data);
    }

    public static  <T> Result<T> ok() {
        return new Result<>();
    }

    public void errorMsg(Integer code,String msg){
        this.code = code;
        this.msg = msg;
    }

    //swagger 3.0 knife4j会解析为errorMsg字段
    public void errorMsg(ErrorCode errorCodeEnum) {
        this.code = errorCodeEnum.getCode();
        this.msg = errorCodeEnum.getMessage();
    }

    public static <T> Result<T> errorRepeat(String msg){
        Result<T> r = new Result<>();
        r.errorMsg(6001, msg);
        return r;
    }

}
